import * as vscode from 'vscode';
import { fileExists, readSettingsFile, writeSettingsFile } from './utils';

// 所有语言的严格模式配置
const strictModeSettings = {
  // JavaScript & TypeScript
  "javascript.validate.enable": true,
  "javascript.implicitProjectConfig.checkJs": true,
  "javascript.format.enable": true,

  "typescript.validate.enable": true,
  "typescript.preferences.importModuleSpecifier": "non-relative",

  // Python
  "python.analysis.typeCheckingMode": "strict",
  "python.analysis.autoSearchPaths": true,
  "python.analysis.useLibraryCodeForTypes": true,
  "python.linting.enabled": true,
  "python.linting.pylintEnabled": true,
  "python.linting.mypyEnabled": true,
  "python.linting.flake8Enabled": false,
  "python.formatting.provider": "black",

  // Java
  "java.errors.incompleteClasspath.severity": "warning",
  "java.import.generatesMetadataFilesAtProjectRoot": false,
  // 可选引导用户配置 java.configuration.runtimes

  // Rust
  "rust-analyzer.checkOnSave.enable": true,
  "rust-analyzer.diagnostics.enable": true,
  "rust-analyzer.cargo.allFeatures": true,
  "rust-analyzer.procMacro.enable": true,

  // Go
  "go.useLanguageServer": true,
  "go.lintTool": "golangci-lint",
  "go.lintOnSave": "file",
  "go.vetOnSave": "file",
  "go.buildOnSave": "package",
  "go.formatTool": "gofmt",
  "go.languageServerExperimentalFeatures": {
    "diagnostics": true
  },

  // C/C++
  "C_Cpp.default.cppStandard": "c++20",
  "C_Cpp.default.cStandard": "c17",
  "C_Cpp.default.warningLevel": "high",
  "C_Cpp.default.intelliSenseMode": "gcc-x64",
  "C_Cpp.errorSquiggles": "enabled",
  "C_Cpp.default.compilerPath": "/usr/bin/g++", // 用户可自定义
  "C_Cpp.default.includePath": ["${workspaceFolder}/**"],

  // 编辑器通用设置
  "editor.formatOnSave": true,
  "editor.formatOnType": true,
  "editor.formatOnPaste": true,
  "editor.codeActionsOnSave": {
    "source.fixAll": "explicit",
    "source.fixAll.eslint": "explicit",
    "source.organizeImports": "explicit"
  },

  // ESLint 状态栏增强
  "eslint.alwaysShowStatus": true
};

export async function createStrictSettingsCommand() {
  const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
  if (!workspaceFolder) {
    vscode.window.showErrorMessage("没有打开项目文件夹");
    return;
  }

  const vscodeDir = vscode.Uri.joinPath(workspaceFolder.uri, ".vscode");
  const settingsFile = vscode.Uri.joinPath(vscodeDir, "settings.json");

  try {
    // 确保 .vscode 存在
    await vscode.workspace.fs.createDirectory(vscodeDir);

    let currentSettings: Record<string, any> = {};
    if (await fileExists(settingsFile)) {
      currentSettings = await readSettingsFile(settingsFile);
    }

    // 合并配置
    const mergedSettings = mergeSettings(currentSettings, strictModeSettings);

    // 写入配置
    await writeSettingsFile(settingsFile, mergedSettings);

    vscode.window.showInformationMessage("已成功合并并写入严格检查设置！");
    await vscode.commands.executeCommand("vscode.open", settingsFile);
  } catch (e: any) {
    vscode.window.showErrorMessage("写入文件失败：" + e.message);
  }
}

function mergeSettings(
  existing: Record<string, any>,
  updates: Record<string, any>
): Record<string, any> {
  // 深度合并两个对象，优先保留原有值，仅添加缺失的项
  const result: Record<string, any> = JSON.parse(JSON.stringify(existing));

  for (const key in updates) {
    if (key === "editor.codeActionsOnSave") {
      // 特殊处理嵌套对象
      result[key] = { ...existing[key], ...updates[key] };
    } else if (!(key in existing)) {
      result[key] = updates[key];
    }
  }

  return result;
}